package com.lagou.rpc.consumer.processor;

import com.lagou.rpc.consumer.annotation.RpcController;
import com.lagou.rpc.consumer.proxy.RpcClientProxy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

    @Autowired
    RpcClientProxy rpcClientProxy;

    //前置处理器
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        //获取class对象
        Class<?> aClass = bean.getClass();
        //通过class对象获取对象属性
        Field[] fields = aClass.getDeclaredFields();
        for (Field field: fields) {
            //获取字段上的注解
            RpcController annotation = field.getAnnotation(RpcController.class);
            if(annotation != null) {
                //创建代理对象
                Object proxy = RpcClientProxy.createProxy(field.getType());

                try {
                    field.setAccessible(true);
                    field.set(bean, proxy);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }

        return bean;
    }
}
